package com.ymatou.iapi.optrade.testcase;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.delivery.parameter.DeliveryInfo;
import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.parameter.req.BatchDeliveryReq;
import com.ymatou.iapi.optrade.parameter.req.DeliverReq;
import com.ymatou.iapi.optrade.parameter.utill.Utils;
import com.ymatou.iapi.optrade.resp.Order;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.optrade.service.BatchDeliveryCall;
import com.ymatou.iapi.optrade.service.RefundService;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.YMTTrading.TradingPlaceOrderCallService;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sharding.model.OrderStatusLogPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.constant.ECode;

/**
 * 批量发货 FreeMaker Template自动生成代码
 * 使用Ts_BatchDispatched用例
 */
@TestSuite
@Ignore
public class Ts_BatchDelivery {
	private static BatchDeliveryReq batchDeliveryReq;
	private static BatchDeliveryCall batchDeliveryCall;
	
	private static OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
	
	private static long userId = 20238699;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("批量发货");
	}

	@Before
	public void caseUp() {

		batchDeliveryReq = new BatchDeliveryReq();
		batchDeliveryCall = new BatchDeliveryCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(batchDeliveryCall.getOpurl());
		orderShardingWapper.activeDeadCommunicationsLink(orderShardingWapper);
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	/**
	 * 校验订单表状态，单主状态操作日志表
	 */
	private void verifyOrderStatus(long orderId, boolean isShippedByXlobo,
			int source, long sellerId) {

		
		// 订单表(order)
		OrderPo ymtOrders = orderShardingWapper.selectOrderbyOrderId(orderId);

		Logger.comment(String.format("验证订单表(order)表 orderId: %s", orderId));

		Logger.verifyEquals(3, ymtOrders.getOrderStatus(), "验证orderStatus");
		Logger.verifyEquals(isShippedByXlobo, ymtOrders.getXloboDelivery(),
				"验证xloboDelivery");

		Logger.verifyEquals(ymtOrders.getLogisticsType() == 7 && source == 2,
				ymtOrders.getDomesticDelivery(), "验证domesticDelivery");

		Logger.verifyEquals(true,
				Utils.calcTimeSpanMin(ymtOrders.getDeliveryTime()) < 2,
				"验证数据库deliveryTime跟系统当前时间差为2分钟内");

		//订单主状态操作日志表(order_status_log)
		OrderStatusLogPo orderStatusLogPo = orderShardingWapper
				.selectOrderStatusLogByOrderId(orderId);

		Logger.comment("验证订单主状态操作日志表(order_status_log)");

		Logger.verifyEquals("发货", orderStatusLogPo.getMemo(), "验证数据库Memo");
		Logger.verifyEquals(3, orderStatusLogPo.getOrderStatus(),
				"验证数据库OrderStatus");

		Logger.verifyEquals(true,
				Utils.calcTimeSpanMin(orderStatusLogPo.getAddTime()) < 2,
				"验证数据库AddTime跟系统当前时间差为2分钟内");

		Logger.verifyEquals(orderId, orderStatusLogPo.getOrderId(),
				"验证数据库OrderId");
		Logger.verifyEquals(sellerId, orderStatusLogPo.getOperator(),
				"验证数据库Operator");

	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_BatchDelivery_001() {
		Logger.start(true, "批量发货成功");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			ArrayList<DeliverReq> dispatchedList = new ArrayList<DeliverReq>();

			TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
					.placeOrderWithThreeProcutInTwoOrder(false,
							BigDecimal.ZERO, userId,
							LogisticsTypeEnum.OVERSEAS_DELIVERY);

			long userId = placeOrderResp.getUserId();

			List<Order> orderList = placeOrderResp.getOrderList();

			for (int i = 0; i < orderList.size(); i++) {

				// 根据交易号支付，只需处理一次即可
				if (i == 0) {

					TradingCallService.payOrder(userId,
							placeOrderResp.getPayableAmount(),
							placeOrderResp.getTradingId());
				}

				Order order = orderList.get(i);

				long orderId = order.getOrderId();
				// 接单
				TradingCallService.sellerAcceptOrder(order.getSellerId(),
						orderId);

				DeliverReq info = new DeliverReq();

				// 物流单号
				String DeliverSummary = TestDataManager.randomStr(10);

				DeliveryInfo deliveryInfo = new DeliveryInfo();

				deliveryInfo.setBillNo(DeliverSummary);
				deliveryInfo.setYmtExpressCode("Y068");
				deliveryInfo.setExpressName("洋码头官方合作物流（贝海国际速递）");

				info.setDeliveryInfos(Arrays.asList(deliveryInfo));

				info.setOrderId(orderId);

				info.setShippedByXlobo(true);
				
				info.setDeliverSummary(DeliverSummary);

				dispatchedList.add(info);
			}
			
			Logger.comment("前置数据准备结束");
			
			// 准备参数
			batchDeliveryReq.setDispatchedList(dispatchedList);

			batchDeliveryCall.setData(batchDeliveryReq);
			batchDeliveryCall.callService();
			Logger.verifyEquals(200, batchDeliveryCall.getCode(),
					"验证code");
			
			// 数据库验证
			for (DeliverReq dispatchedInfo : batchDeliveryReq
					.getDispatchedList()) {

				long orderId = dispatchedInfo.getOrderId();

				verifyOrderStatus(orderId, dispatchedInfo.isShippedByXlobo(),
						dispatchedInfo.getSource(),
						dispatchedInfo.getSellerId());
			}

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_BatchDelivery_002() {
		Logger.start(false, "订单不存在");
		try {
			ArrayList<DeliverReq> dispatchedList = new ArrayList<DeliverReq>();

			long orderId = 123;
			DeliverReq info = new DeliverReq();

			// 物流单号
			String DeliverSummary = TestDataManager.randomStr(10);

			DeliveryInfo deliveryInfo = new DeliveryInfo();

			deliveryInfo.setBillNo(DeliverSummary);
			deliveryInfo.setYmtExpressCode("Y068");
			deliveryInfo.setExpressName("洋码头官方合作物流（贝海国际速递）");

			info.setDeliveryInfos(Arrays.asList(deliveryInfo));

			info.setOrderId(orderId);

			dispatchedList.add(info);
			// 准备参数
			batchDeliveryReq.setDispatchedList(dispatchedList);
			batchDeliveryCall.setData(batchDeliveryReq);
			batchDeliveryCall.callService();
			Logger.verifyEquals(200, batchDeliveryCall.getCode(),
					"验证Code");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_BatchDelivery_003() {
		Logger.start(true, "当前订单状态不能发货");
		try {
			Logger.comment("前置数据准备");
			ArrayList<DeliverReq> dispatchedList = new ArrayList<DeliverReq>();
			// 创建订单
			TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
					.placeOrderWithThreeProcutInTwoOrder(false,
							BigDecimal.ZERO, userId,
							LogisticsTypeEnum.OVERSEAS_DELIVERY);

			long userId = placeOrderResp.getUserId();

			List<Order> orderList = placeOrderResp.getOrderList();

			for (int i = 0; i < orderList.size(); i++) {
				// 根据交易号支付，只需处理一次即可
				if (i == 0) {

					TradingCallService.payOrder(userId,
							placeOrderResp.getPayableAmount(),
							placeOrderResp.getTradingId());

				}
				long orderId = orderList.get(i).getOrderId();
				// 接单

				DeliverReq info = new DeliverReq();

				// 物流单号
				String DeliverSummary = TestDataManager.randomStr(10);

				DeliveryInfo deliveryInfo = new DeliveryInfo();

				deliveryInfo.setBillNo(DeliverSummary);
				deliveryInfo.setYmtExpressCode("Y068");
				deliveryInfo.setExpressName("洋码头官方合作物流（贝海国际速递）");

				info.setDeliveryInfos(Arrays.asList(deliveryInfo));

				info.setOrderId(orderId);

				dispatchedList.add(info);
			}
			// 准备参数
			Logger.comment("前置数据准备结束");
			batchDeliveryReq.setDispatchedList(dispatchedList);
			batchDeliveryCall.setData(batchDeliveryReq);
			batchDeliveryCall.callService();
			Logger.verifyEquals(201, batchDeliveryCall.getCode(),
					"验证Code");
			Logger.verifyEquals("当前状态2不能发货.", batchDeliveryCall.getMsg(),
					"验证Msg包含信息:" + ECode.FAILED201_MSG_28);
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_BatchDelivery_004() {
		Logger.start(true, "发货信息列表信息为null");
		try {
			batchDeliveryReq.setDispatchedList(null);
			batchDeliveryCall.setData(batchDeliveryReq);
			batchDeliveryCall.callService();
			Logger.verifyEquals(400, batchDeliveryCall.getCode(),
					"验证Code");
			Logger.verifyIsContains("发货信息列表不能为空", batchDeliveryCall.getMsg(),
					"验证Msg");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_BatchDelivery_005() {
		Logger.start(true, "订单号不存在");
		try {
			ArrayList<DeliverReq> dispatchedList = new ArrayList<DeliverReq>();

			DeliverReq info = new DeliverReq();

			// 物流单号
			String DeliverSummary = TestDataManager.randomStr(10);

			DeliveryInfo deliveryInfo = new DeliveryInfo();

			deliveryInfo.setBillNo(DeliverSummary);
			deliveryInfo.setYmtExpressCode("Y068");
			deliveryInfo.setExpressName("洋码头官方合作物流（贝海国际速递）");

			info.setDeliveryInfos(Arrays.asList(deliveryInfo));

			info.setOrderId(1111);

			dispatchedList.add(info);
			// 准备参数
			batchDeliveryReq.setDispatchedList(dispatchedList);
			batchDeliveryCall.setData(batchDeliveryReq);
			batchDeliveryCall.callService();
			Logger.verifyEquals(200, batchDeliveryCall.getCode(),
					"验证Code");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_BatchDelivery_006() {
		Logger.start(true, "当前订单为退货退款中,批量发货失败");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			ArrayList<DeliverReq> dispatchedList = new ArrayList<DeliverReq>();

			TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
					.placeOrderWithThreeProcutInTwoOrder(false,
							BigDecimal.ZERO, userId,
							LogisticsTypeEnum.OVERSEAS_DELIVERY);

			long userId = placeOrderResp.getUserId();

			List<Order> orderList = placeOrderResp.getOrderList();

			for (int i = 0; i < orderList.size(); i++) {
				// 根据交易号支付，只需处理一次即可
				if (i == 0) {

					TradingCallService.payOrder(userId,
							placeOrderResp.getPayableAmount(),
							placeOrderResp.getTradingId());

				}
				long orderId = orderList.get(i).getOrderId();

				// 接单
				TradingCallService.sellerAcceptOrder(orderList.get(i)
						.getSellerId(), orderId);

				RefundService.applyRefund(orderList.get(i));

				DeliverReq info = new DeliverReq();

				// 物流单号
				String DeliverSummary = TestDataManager.randomStr(10);

				DeliveryInfo deliveryInfo = new DeliveryInfo();

				deliveryInfo.setBillNo(DeliverSummary);
				deliveryInfo.setYmtExpressCode("Y068");
				deliveryInfo.setExpressName("洋码头官方合作物流（贝海国际速递）");

				info.setDeliveryInfos(Arrays.asList(deliveryInfo));

				info.setOrderId(orderId);

				dispatchedList.add(info);
			}
			Logger.comment("前置数据准备结束");
			// 准备参数
			batchDeliveryReq.setDispatchedList(dispatchedList);
			batchDeliveryCall.setData(batchDeliveryReq);
			batchDeliveryCall.callService();

			Logger.verifyEquals(201, batchDeliveryCall.getCode(),
					"验证Code");
			Logger.verifyEquals("102", batchDeliveryCall.getBCode(), "验证bcode");

			Logger.verifyEquals("哈尼，此单有退货/退款，请先去处理~",
					batchDeliveryCall.getMsg(), "验证Msg");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_BatchDelivery_007() {
		Logger.start(true, "批量发货,其中有订单状态为不能发货");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			ArrayList<DeliverReq> dispatchedList = new ArrayList<DeliverReq>();

			TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
					.placeOrderWithThreeProcutInTwoOrder(false,
							BigDecimal.ZERO, userId,
							LogisticsTypeEnum.OVERSEAS_DELIVERY);

			long userId = placeOrderResp.getUserId();

			List<Order> orderList = placeOrderResp.getOrderList();

			for (int i = 0; i < orderList.size(); i++) {

				// 根据交易号支付，只需处理一次即可
				if (i == 0) {

					TradingCallService.payOrder(userId,
							placeOrderResp.getPayableAmount(),
							placeOrderResp.getTradingId());

				}

				Order order = orderList.get(i);

				long orderId = order.getOrderId();

				if (i != 0) {
					// 接单
					TradingCallService.sellerAcceptOrder(order.getSellerId(),
							orderId);

				}

				DeliverReq info = new DeliverReq();

				// 物流单号
				String DeliverSummary = TestDataManager.randomStr(10);

				DeliveryInfo deliveryInfo = new DeliveryInfo();

				deliveryInfo.setBillNo(DeliverSummary);
				deliveryInfo.setYmtExpressCode("Y068");
				deliveryInfo.setExpressName("洋码头官方合作物流（贝海国际速递）");

				info.setDeliveryInfos(Arrays.asList(deliveryInfo));

				info.setOrderId(orderId);

				info.setShippedByXlobo(true);

				dispatchedList.add(info);
			}
			Logger.comment("前置数据准备结束");
			// 准备参数
			batchDeliveryReq.setDispatchedList(dispatchedList);

			batchDeliveryCall.setData(batchDeliveryReq);
			batchDeliveryCall.callService();

			// 数据库验证
			Logger.verifyEquals(201, batchDeliveryCall.getCode(),
					"验证Code");
			Logger.verifyEquals("当前状态2不能发货.", batchDeliveryCall.getMsg(),
					"验证Msg包含信息:" + ECode.FAILED201_MSG_28);
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}
